package com.ocom.common.entity.typehandler;

import com.ocom.common.utils.DESUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class MngUserHandle extends BaseTypeHandler<String> {

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
		if (StringUtils.isNotBlank(parameter)) {
			ps.setString(i, encrypt(parameter));
		} else {
			ps.setString(i, "");
		}
	}

	@Override
	public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
		String columnValue = decrypt(rs.getString(columnName));
		return columnValue;
	}

	@Override
	public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		String columnValue = rs.getString(columnIndex);
		return decrypt(columnValue);
	}

	@Override
	public String getNullableResult(CallableStatement cs, int columnIndex)
			throws SQLException {
		String columnValue = cs.getString(columnIndex);
		return decrypt(columnValue);
	}

	private String encrypt(String parameter) {
		String value = parameter;
		try {
			value = DESUtils.encrypt(parameter,"4MkgDpxpMhZpQUdZeKGHgfzfzUT2QhQd");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return value;
	}

	public String decrypt(String parameter) {
		String value = parameter;
		try {
			value = DESUtils.decrypt(parameter,"4MkgDpxpMhZpQUdZeKGHgfzfzUT2QhQd");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return value;
	}
}

